import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/models/file_search_list_entity.dart';
import 'package:seedfour/app/theme.dart';

import '../../constants.dart';
import 'logic.dart';

class FileSearchPage extends StatelessWidget {
  FileSearchPage({Key? key}) : super(key: key);

  final logic = Get.find<FileSearchLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('文件检索'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: _buildBg(children: [
        _buildSearchBar(),
        Obx(() => logic.isLoading.value
            ? const Center(child: CircularProgressIndicator())
            : _buildFileList()),
      ]),
    );
  }

  Widget _valueText(String? value) {
    return Container(
      margin: EdgeInsets.only(
          right: kSpaceSmall, top: kSpaceMini, left: kSpaceTiny * 2),
      child: Text(
        textAlign: TextAlign.right,
        value ?? '',
        style: TextStyle(
          fontSize: kFontSizeSmall,
          color: Colors.black87,
        ),
      ),
    );
  }

  Widget _labelText(String value) {
    return Container(
      margin: EdgeInsets.only(right: kSpaceSmall, top: kSpaceMini),
      width: Get.width / 5,
      child: Text(
        textAlign: TextAlign.end,
        value,
        style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
      ),
    );
  }

  Widget _buildListItem(FileSearchData item) {
    return Column(
      children: [
        Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('文件名'),
              Expanded(child: Html(data: item.fileName))
            ]),
        SizedBox(height: kSpaceTiny),
        Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('文件类型'),
              _valueText(fileTypes[item.deliveryType] ?? '')
            ]),
        SizedBox(height: kSpaceTiny),
        Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('所属案件/目录'),
              Expanded(child: Html(data: item.name ?? ''))
            ]),
        SizedBox(height: kSpaceTiny),
        Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('文件备注'),
              Expanded(child: Html(data: item.remark ?? ''))
            ]),
        SizedBox(height: kSpaceTiny),
        Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('经手人'),
              Expanded(child: Html(data: item.takername ?? ''))
            ]),
        SizedBox(height: kSpaceTiny),
        Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _labelText('上传时间'),
              _valueText(DateFormat('yyyy-MM-dd HH:mm')
                  .format(DateTime.fromMillisecondsSinceEpoch(item.createdAt!)))
            ]),
      ],
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < logic.files.length) {
      return Padding(
        padding:
            EdgeInsets.symmetric(vertical: kSpaceSmall, horizontal: kSpaceTiny),
        child: _buildListItem(logic.files[index]),
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _buildFileList() {
    return Expanded(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: kSpaceSmall),
        child: Ink(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(kSpaceSmall),
          ),
          child: Obx(
            () => ListView.separated(
                controller: logic.scrollController,
                itemBuilder: _renderRow,
                separatorBuilder: (BuildContext context, int index) =>
                    const Divider(),
                itemCount: logic.files.length + 1),
          ),
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.all(kSpaceMedium),
      padding: EdgeInsets.all(kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '姓名',
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
              ),
            ),
            Expanded(
              child: TextField(
                textAlign: TextAlign.end,
                controller: logic.userNameText,
                decoration: InputDecoration(
                  hintText: '请输入',
                  hintStyle: TextStyle(
                    color: AppColor.colorFontLabelGrey,
                    fontSize: kFontSizeSmall,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(kRadiusSmall),
                    borderSide: BorderSide.none,
                  ),
                  contentPadding: EdgeInsets.symmetric(
                      horizontal: kSpaceSmall, vertical: kSpaceMini),
                ),
              ),
            ),
          ],
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '文件类型',
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
              ),
            ),
            Obx(
              () => Expanded(
                child: DropdownButton(
                  alignment: Alignment.centerRight,
                  value: logic.fileType.value,
                  hint: Text(
                    '请选择',
                    style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontLabelGrey),
                  ),
                  icon: const Icon(Icons.keyboard_arrow_down_rounded),
                  isExpanded: true,
                  underline: Container(),
                  items: fileTypes.entries
                      .map((e) => DropdownMenuItem(
                            value: e.key,
                            child: Text(e.value),
                          ))
                      .toList(),
                  onChanged: (value) => logic.selectFileType(value!),
                ),
              ),
            ),
          ],
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '名称',
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
              ),
            ),
            Expanded(
              child: TextField(
                textAlign: TextAlign.end,
                controller: logic.caseNameText,
                decoration: InputDecoration(
                  hintText: '文件名/文件备注/案件名/目录名',
                  hintStyle: TextStyle(
                    color: AppColor.colorFontLabelGrey,
                    fontSize: kFontSizeSmall,
                  ),
                  border: InputBorder.none,
                ),
              ),
            ),
          ],
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '关键词',
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeSmall,
              ),
            ),
            Expanded(
              child: TextField(
                textAlign: TextAlign.end,
                controller: logic.keywordText,
                decoration: InputDecoration(
                  hintText: '请输入',
                  hintStyle: TextStyle(
                    color: AppColor.colorFontLabelGrey,
                    fontSize: kFontSizeSmall,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(kRadiusSmall),
                    borderSide: BorderSide.none,
                  ),
                  contentPadding: EdgeInsets.symmetric(
                      horizontal: kSpaceSmall, vertical: kSpaceMini),
                ),
              ),
            ),
          ],
        ),

        SizedBox(height: kSpaceSmall),
        // 搜索按钮
        FilledButton(
          onPressed: () => logic.onSearch(),
          child: const Text('检索'),
        ),
      ]),
    );
  }

  Widget _buildBg({required List<Widget> children}) {
    return Column(children: children);
  }
}
